package pl.elka.pobr.ppr.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.ScrollPane;

import javax.swing.JFrame;
import javax.swing.JPanel;

import pl.elka.pobr.ppr.utils.Log;

public class HistogramFrame extends JFrame {

    public HistogramFrame(final int[][] histogram) {
        setLocation(100, 100);
        int fw = 320;
        int fh = 400;
        final int pw = 260;
        int ph = 3 * 265;
        // normalize histogram values to 255 max
        final int[][] normalizedHist = new int[histogram.length][histogram[0].length];
        int[] maxValues = new int[3];
        for (int i = 0; i < histogram.length; ++i) {
            for (int j = 0; j < histogram[i].length; ++j) {
                if (maxValues[i] < histogram[i][j]) {
                    maxValues[i] = histogram[i][j];
                }
            }
        }
        Log.d("HistogramFrame", "hist max r,g,b = " + maxValues[0] + "," + maxValues[1] + "," + maxValues[2]);
        for (int i = 0; i < histogram.length; ++i) {
            for (int j = 0; j < histogram[i].length; ++j) {
                normalizedHist[i][j] = histogram[i][j] * 255 / maxValues[i];
            }
        }
        JPanel p = new JPanel() {

            @Override
            public void paint(Graphics g) {
                super.paint(g);
                for (int i = 0; i < normalizedHist.length; ++i) {
                    Color c = Color.RED;
                    if (i == 1) {
                        c = Color.GREEN;
                    } else if (i == 2) {
                        c = Color.BLUE;
                    }
                    int h = (i + 1) * 260; // bottom edge for this color
                    g.setColor(Color.BLACK);
                    g.drawLine(10, h + 1, 265, h + 1); // horizontal line
                    for (int j = 0; j < normalizedHist[i].length; ++j) {
                        g.setColor(c);
                        g.drawLine(10 + j, h, 10 + j, h - normalizedHist[i][j]);
                    }
                }
            }
        };
        Container con = getContentPane();
        p.setPreferredSize(new Dimension(pw, ph));
        ScrollPane scroll = new ScrollPane();
        scroll.add(p);
        con.add(scroll, BorderLayout.CENTER);
        setSize(fw, fh);
        setPreferredSize(new Dimension(fw, fh));
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }
}
